import java.util.*;

class WordSearcher {
    private Set<WordPair> wordPairs = new HashSet<>();

    Map<String, Optional<WordLocation>> search(Set<String> searchWords, char[][] chars) {
        Map<String, Optional<WordLocation>> results = new HashMap<>();

        this.makeWordPairs(chars);

        searchWords.forEach((String word) -> {
            String[] letters = word.split("");
            Set<WordLocation> prepareWordLoaction = new HashSet<>();

            int length = letters.length;

            Set<WordPair> firstLetters = this.findLetter(letters[0]);
            Set<WordPair> lastLetters = this.findLetter(letters[letters.length - 1]);
            firstLetters.forEach((WordPair first) -> lastLetters.forEach((WordPair last) -> {
                if ((first.x - last.x == 0 || (Math.abs(first.x - last.x) == length - 1))
                        && (first.y - last.y == 0 || (Math.abs(first.y - last.y) == length - 1))) {
                    prepareWordLoaction.add(new WordLocation(new Pair(first.x, first.y), new Pair(last.x, last.y)));
//                    results.put(word, Optional.of(new WordLocation(new Pair(first.x, first.y), new Pair(last.x, last.y))));
                }
            }));


        });

        return results;
    }

    private WordLocation findWordLocation(WordPair firstPair, WordPair lastPair, String[] letters) {

    }

    private void makeWordPairs(char[][] chars) {
        for (int i = 0; i < chars.length; i++) {
            for (int j = 0; j < chars[i].length; j++) {
                this.wordPairs.add(new WordPair(j + 1, i + 1, String.valueOf(chars[i][j])));
            }
        }

    }

    private Set<WordPair> findLetter(String lastLetter) {
        Set<WordPair> pairs = new HashSet<>();
        this.wordPairs.forEach(pair -> {
            if (pair.letter.equals(lastLetter)) pairs.add(pair);
        });

        return pairs;
    }

    class WordPair {
        private final int x;
        private final int y;
        private final String letter;

        WordPair(int x, int y, String letter) {

            this.x = x;
            this.y = y;
            this.letter = letter;
        }

        @Override
        public boolean equals(final Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            WordPair pair = (WordPair) o;

            return x == pair.x && y == pair.y;
        }

        @Override
        public int hashCode() {
            int result = x;
            result = 31 * result + y;
            return result;
        }
    }
}
